const { Controller } = require('egg');

class AwardKindController extends Controller {
  async list() {
    const awardKinds = await this.service.awardKind.list();
    this.ctx.helper.success(awardKinds);
  }

  async create() {
    const { ctx, service } = this;
    const { kindTitle, isLatest } = ctx.request.body;

    if (!kindTitle) {
      return this.ctx.helper.error("kindTitle 不能为空");
    }

    const result = await service.awardKind.create({
      kindTitle,
      isLatest,
    });
    this.ctx.helper.success(result, "获奖种类创建成功");
  }

  async delete() {
    const { ctx, service } = this;
    const { kindId } = ctx.request.body;

    if (!kindId) {
      return this.ctx.helper.error("参数异常：缺少 kindId");
    }
    const result = await service.awardKind.delete({ kindId });
    if (result === 0) {
      return this.ctx.helper.error("删除失败，获奖种类不存在");
    }
    this.ctx.helper.success(result, "获奖种类删除成功");
  }

  async update() {
    const { ctx, service } = this;
    const { kindTitle, isLatest, kindId } = ctx.request.body;

    if (!kindId) {
      return this.ctx.helper.error("参数异常：缺少获奖种类 ID");
    }
    const result = await service.awardKind.update({ kindId }, { kindTitle, isLatest });
    if (result[0] === 0) {
      return this.ctx.helper.error("更新失败，获奖种类不存在");
    }
    this.ctx.helper.success(result, "获奖种类更新成功");
  }

  async setLatest() {
    const { ctx, service } = this;
    const { id } = ctx.request.body;

    if (!id) {
      return this.ctx.helper.error("参数异常：缺少 id");
    }

    const result = await service.awardKind.setLatest(id);
    if (result === 0) {
      return this.ctx.helper.error("设置失败，获奖种类不存在");
    }
    this.ctx.helper.success(result, "设置为最新成功");
  }
}

module.exports = AwardKindController;